﻿import { Component, EventEmitter, Output } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormControl, Validators, FormBuilder }
    from '@angular/forms';
import { Http, Headers } from '@angular/http';
import { AppServiceMembership } from '../../services/app.service.membership'

@Component({
    selector: 'login',
    templateUrl: './app/components/login/login.component.html',
    styleUrls: ['./app/components/login/login.component.css']
})
export class LoginComponent {
    loginForm: FormGroup;
    @Output() showUserInfo = new EventEmitter();
    constructor(public fb: FormBuilder, private appServiceMembership: AppServiceMembership, private router: Router) {
        this.loginForm = fb.group({
            'username': [null, Validators.required],
            'password': [null, Validators.compose([Validators.required, Validators.maxLength(6)])],
        });

    }
    login(form: any): void {
        this.appServiceMembership.login(form, res => {
            let data = res.json();
            this.appServiceMembership.saveCredentials(form);
            this.showUserInfo.emit({ value: data.username });
            if (this.appServiceMembership.isLoggedIn) {
                let redirect: string = this.appServiceMembership.redirectUrl ? this.appServiceMembership.redirectUrl : '/home';
                this.router.navigate([redirect]);
            }
        });
    }
}




